package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.fgs.common.CommonResponse;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.dialog.OperateTipDialog;
import com.google.gson.Gson;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.contract.OrderListContract;
import com.tianhui.consignortwofei.mvp.model.GoodsModel;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.BoHuiBodyBean;
import com.tianhui.consignortwofei.mvp.model.enty.GoodsInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.enty.ToExamineInfo;
import com.tianhui.consignortwofei.mvp.presenter.OrderListPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.FindCarOnlyLookActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.lite.ChangeFindCarActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.lite.EditFindCarLiteDeliverActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.ToExamineListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderStatus.status.IOrderStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.DaiQueRenExamineStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.QueRenExamineStatus;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class ToExamineListFragment extends SearchFragment<OrderListContract.View, OrderListContract.Presenter> implements OrderListContract.View {

    private boolean isNeedLazyLoad = true;
    private IOrderStatus mIOrderStatus;
    private String mSearchKey;
    private int rolePosition;// //2 销售，3物流
    private int which;

    public ToExamineListFragment() {
        // Required empty public constructor
    }

    @Override
    protected void changeSearchKey(String searchKey) {
        mSearchKey = searchKey;
    }

    @Override
    public boolean isNeedLazyLoad() {
        return this.isNeedLazyLoad;
    }

    public static ToExamineListFragment newInstance(IOrderStatus iOrderStatus,int which) {
        ToExamineListFragment orderListFragment = new ToExamineListFragment();
        orderListFragment.setOrderStatus(iOrderStatus,which);
        return orderListFragment;
    }

    private ToExamineListFragment setOrderStatus(IOrderStatus iOrderStatus,int inWhich) {
        mIOrderStatus = iOrderStatus;
        which=inWhich;
        return this;
    }

    public ToExamineListFragment setIsNeedLazyLoad(boolean isNeedLazyLoad) {
        this.isNeedLazyLoad = isNeedLazyLoad;
        return this;
    }

    public ToExamineListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }


    @Override
    protected OrderListContract.View createView() {
        return this;
    }

    @Override
    protected OrderListContract.Presenter createPresenter() {
        return new OrderListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
//        return new OrderListAdapter(getContext(), mIOrderStatus);
        rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
        return new ToExamineListAdapter(getContext(), mIOrderStatus, rolePosition,which);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Object object = mAdapter.getAllData().get(position);
                if (object instanceof ToExamineInfo) {
                    ToExamineInfo examineInfo = (ToExamineInfo) object;

                    if (mIOrderStatus instanceof DaiQueRenExamineStatus){
                        examineInfo.status="99";
                    }else if (mIOrderStatus instanceof QueRenExamineStatus){
                        examineInfo.status="98";
                    }
                    if (5==which) {
                        examineInfo.leftquantity = "";
                    }
                    examineInfo.which=which;
                    Gson gson=new Gson();
                    String json = gson.toJson(examineInfo);
                    Bundle bundle=new Bundle();
                    bundle.putString("toexamine",json);

//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                    bundle.putString("", mIOrderStatus.getOrderStatusType());

//                    if (2==rolePosition){
//                        //2 销售，3物流
//                    if (4==which||5==which){
//                        openActivity(CarSearchAuditActivity.class, bundle);
//                    }else {
                        openActivity(FindCarOnlyLookActivity.class, bundle);
//                    }

//                    }else {
//                        //0 待审核、1已经审核 2退回,3作废
//                        if ("0".equals(examineInfo.status)){
//                            openActivity(CarSearchAuditActivity.class, bundle);
//                        } else {
//                            openActivity(FindCarOnlyLookActivity.class, bundle);
//                        }
//                    }



                }

            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                ToExamineInfo examineInfo = null;
                if (object instanceof ToExamineInfo) {
                    examineInfo = (ToExamineInfo) object;
                }
                Gson gson=new Gson();
                String json = gson.toJson(examineInfo);
                GoodsInfo  mGoodsInfo = gson.fromJson(json, GoodsInfo.class);
                switch (view.getId()) {
                    case R.id.tv_quxiao:
                        if (examineInfo != null) {
                           showDelete(mGoodsInfo);
                        }
                        break;
                    case R.id.tv_liulan:
                        if (examineInfo != null) {
                            showTerminateDialog(getActivity(),mGoodsInfo);
                        }
                        break;
                    case R.id.tv_bainji:

                        String json2 = gson.toJson(examineInfo);
                        Bundle bundle=new Bundle();
                        bundle.putString("erpdetails",json2);
                        openActivity(EditFindCarLiteDeliverActivity.class,bundle);
                        break;
                    case R.id.tv_bainji_huozhu:
                        String jsonChange = gson.toJson(examineInfo);
                        Bundle bundleChange=new Bundle();
                        bundleChange.putString("erpdetails",jsonChange);
                        openActivity(ChangeFindCarActivity.class,bundleChange);
                        break;
                    case R.id.tv_zhuan_yan:
                        if (examineInfo != null) {
                            showZhuanYan(mGoodsInfo);
                        }
                        break;
                    case R.id.tv_queren:
                        if (examineInfo != null) {
                            showQueRenDiolog(mGoodsInfo,"确定要确认单据吗？","1");
                        }
                        break;
                    case R.id.tv_quxiao_queren:
                        if (examineInfo != null) {
                            showQueRenDiolog(mGoodsInfo,"确定要取消确认单据吗？","0");
                        }
                        break;

                }
            }



//                switch (view.getId()) {
////                    case R.id.item_order_list_submitTextView:
////                        if (orderInfo != null) {
////                            Bundle bundle = new Bundle();
////                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
////                            bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
////                            openActivity(OrderDetailActivity.class, bundle);
////                        }
////
////                        break;
////                    case R.id.ll_driver_line_body://分享码
////                        if (orderInfo != null) {
////                            showShareCode(orderInfo);
////                        }
////                        break;
//
//                    case R.id.tv_liulan:
//
//                        showTerminateDialog(getActivity());
//
////                        if (orderInfo != null) {
////                            Bundle bundle = new Bundle();
////                            bundle.putString("sourcenum", orderInfo.billno);
////                            openActivity(LiuLanLogActivity.class, bundle);
////                        }
////                        Toast.makeText(getContext(), "浏览记录", Toast.LENGTH_SHORT).show();
//                        break;
//                }

        });

    }



//    private void showShareCode(OrderInfo orderInfo) {
//        new PermissionHelper().checkPermissions((FragmentActivity) getContext(), new OnPermissionCheckResult() {
//            @Override
//            public void grantedResult() {
//
//                if (!TextUtils.isEmpty(orderInfo.billno)) {
//                    String base64BillNo = Base64Utils.encode(orderInfo.billno);
//                    Bitmap bitmap = createQRCodeWithLogo(base64BillNo, ImageUtils.getBitmap(R.mipmap.icon_app));
//                    new QRCodeDialog(getContext(), bitmap).show();
//                } else {
//                    showToast("获取订单信息失败");
//                }
//
//            }
//
//            @Override
//            public void shouldShowRequestPermissionRationale() {
//
//            }
//
//            @Override
//            public void grantedForbidResult() {
//
//            }
//        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//    }

//    /**
//     * 生成简单的带logo的二维码
//     *
//     * @param content
//     * @param logo
//     */
//    @IOThread(ThreadType.Single)
//    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
//        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
//        return bitmap;
//    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog);
        }
    }

    @Override
    public void initData() {

        if (mIOrderStatus != null)
            setSearchKeyHint("按销货单号,销售员进行查询");
//            setSearchKeyHint(mIOrderStatus.getSearchHint());
    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_ORDER_LIST:
                if (isHasLoadData())
                    refreshData(false);
                break;
        }
    }


    private void showTerminateDialog(Context context,GoodsInfo  mGoodsInfo) {
        new OperateTipDialog.Builder(context)
                .title("请输入驳回原因")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入驳回原因");
                            return;
                        }
                        dialog.dismiss();
                        sendFindCarList(mGoodsInfo);

                    }
                })
                .show();
    }


    private void sendFindCarList(GoodsInfo mGoodsInfo) {
        GoodsModel  mModel = new GoodsModel();
        mModel.sendFindCarList(getActivity(), mGoodsInfo, true, bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
//                    publicGoodsSuccess();
                    String searchKey = mSearchKeyEditText.getText().toString().trim();
                    try {
                        searchKey=searchKey.replaceAll(" +","");
                    }catch (Exception e){
                        LogUtil.print(e.toString());
                    }
                    requestSearch(searchKey);
                } else {
                    setMsg(commonResponse.getMsg());
                }


            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });

    }

    private void showDelete(GoodsInfo  mGoodsInfo) {
        new MaterialDialog.Builder(getContext())
                .content("确定要删除找车单吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                        tongYiFaDan(mGoodsInfo);
                    }
                })
                .show();
    }

    private void tongYiFaDan(GoodsInfo  mGoodsInfo) {

        GoodsModel mModel = new GoodsModel();
        BoHuiBodyBean boHuiBodyBean = new BoHuiBodyBean(mGoodsInfo.id, "删除", "4");

        mModel.boHuiZhaoChe(getActivity(), boHuiBodyBean, true, bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    showToast("删除成功");
                    EventBusManage.refreshOrderList();

                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });
    }


    private void showZhuanYan(GoodsInfo  mGoodsInfo) {
        new MaterialDialog.Builder(getContext())
                .content("确定要将单子转给延长吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                        zhuanYanChang(mGoodsInfo);
                    }
                })
                .show();
    }

    private void zhuanYanChang(GoodsInfo  mGoodsInfo) {

        Map<String, String> map = new HashMap<>();
        map.put("id", mGoodsInfo.id);
        map.put("isOut", "1");
        new OrderModel().zhuanYanChang(getActivity(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                    if (commonResponse.getCode() == 20000) {
                        showToast("转单成功");
                        EventBusManage.refreshOrderList();
                    } else {
                        showToast(commonResponse.getMsg());
                    }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });


    }


    private void showQueRenDiolog(GoodsInfo  mGoodsInfo ,String title,String type) {
        new MaterialDialog.Builder(getContext())
                .content(title)
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                        queRenDingDan(mGoodsInfo,type);
                    }
                })
                .show();
    }


    private void queRenDingDan(GoodsInfo  mGoodsInfo,String type) {

        Map<String, String> map = new HashMap<>();
        map.put("id", mGoodsInfo.id);
        map.put("isTrue", type);
        new OrderModel().queRenDingDan(getActivity(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    showToast("操作成功");
                    EventBusManage.refreshOrderList();
                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });


    }






}
